//
//  UIImage+Extension.swift
//  weibo
//
//  Created by huxuedong on 15/12/9.
//  Copyright © 2015年 huxuedong. All rights reserved.
//

import UIKit

extension UIImage {
    
    //获取启动图片
    class func getLaunchImage() -> UIImage? {
        let infoDict = NSBundle.mainBundle().infoDictionary
        //[[String: AnyObject]]的本质是数组，其中存放的元素是字典
        guard let images = infoDict?["UILaunchImages"] as? [[String: AnyObject]] else {
            return nil
        }
        let screenSize = UIScreen.mainScreen().bounds.size
        //遍历数组，获取当前屏幕对应的启动图
        for imageDict in images {
            guard let sizeString = imageDict["UILaunchImageSize"] as? String else {
                break
            }
            let size = CGSizeFromString(sizeString)
            if CGSizeEqualToSize(screenSize, size) {
                let image = UIImage(named: (imageDict["UILaunchImageName"] as! String))
                return image
            }
        }
        return nil
    }
    
    //获取屏幕截图
    class func cutOffPicture() -> UIImage {
        let window = UIApplication.sharedApplication().keyWindow!
        //开启图片上下文
        UIGraphicsBeginImageContext(window.size)
        //将window的内容渲染到图片上下文中
        window.drawViewHierarchyInRect(window.bounds, afterScreenUpdates: false)
        //获取到图片上下文中的内容
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //关闭图片上下文
        UIGraphicsEndImageContext()
        return image
    }
    
    //等比例缩放图片到指定宽度
    func scaleToWidth(width: CGFloat) -> UIImage {
        if size.width < width {
            return self
        }
        //计算缩放后图片宽度
        let height = width / size.width * size.height
        let rect = CGRect(x: 0, y: 0, width: width, height: height)
        //开启上下文
        UIGraphicsBeginImageContext(rect.size)
        //将图片绘制到上下文中
        drawInRect(rect)
        //从上下文中获取到图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        return image
    }
    
}
